import router from './index'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { getToken } from '@/utils/token'
import config from '@/config'

const whiteList = ['login', 'register']

// 简单配置
NProgress.inc(0.2)
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false })

router.beforeEach((to, from, next) => {
  NProgress.start()

  document.title = to.meta.title ? `${config.title}-${to.meta.title}` : config.title

  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: from.path || '/home', replace: true })
      NProgress.done()
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.name)) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

router.onError(error => {
  const pattern = /Loading chunk ([0-9a-zA-Z-])+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  if (isChunkLoadFailed) {
    location.reload(true)
  }
})
